import { ParseCars } from "./car.js";

const MAIN_CAR_INDEX = 0;

export class Problem {
    constructor( problem_id ) {
        this.problem_id = problem_id;
        this.cars = [];
        this.rank_list = [];
        this.name = '第' + problem_id + '关';
        this.cars_json_copy = null;
    }

    GetProblem() {
        $.ajax( {
            async: false,
            type: "GET",
            url: "/data/problem?problem_id=" + this.problem_id,
            success: ( resp, status, xhr ) => {
                this.cars = ParseCars( resp.cars );
                this.cars_json_copy = resp.cars;
                /* this.name = resp.name; */ // For future use.
            },
            error: function ( xhr, status, error ) {
                console.log( error );
            }
        } );
    }

    GetRankList() {
        $.ajax( {
            async: false,
            type: "GET",
            url: "/data/rank_list?problem_id=" + this.problem_id,
            dataType: "json",
            success: ( resp, status, xhr ) => {
                this.rank_list = resp.rank_list;
            },
            error: function ( xhr, status, error ) {
                console.log( error );
            }
        } );
    }

    IsSolved() {
        if ( this.cars.length < 1 ) {
            return false;
        }

        let the_main_car = this.cars[ MAIN_CAR_INDEX ];
        return ( the_main_car.x === 6 || the_main_car.x === 7 ) && the_main_car.y === 2;
    }

    IsGotSuccess() {
        return this.cars.length > 0;
    }

    ResetCars() {
        this.cars = ParseCars( this.cars_json_copy );
    }
}